<?php

namespace App\Http\Controllers;

use App\Imports\ScoreImport;
use App\Models\Score;
use App\Models\Student;
use App\Models\Subject;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class ScoreController extends Controller
{
    public function scoreSubjectDetails(Request $request)
    {
        $subject_id = $request->subject_id;
        $test_date = $request->test_date;

        $scores = Score::query()
            ->where('subject_id', $subject_id)
            ->where('test_date', $test_date)
            ->with(['student', 'subject'])
            ->orderBy('score', 'desc')
            ->paginate(10);
        return response()->json(['data' => $scores], 200);
    }

    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $query = Score::query()->with(['student', 'subject']);
        if ($student_id = $request->student_id) {
            $query->where('student_id', $student_id);
        }
        if ($subject_id = $request->subject_id) {
            $query->where('subject_id', $subject_id);
        }
        return response()->json(['data' => $query->paginate(10)], 200);
    }

    public function studentScores(Request $request)
    {
        $student_id = $request->student_id;
        $subject_ids = $request->subject_ids;
        $query = Score::query();
        if ($subject_ids) {

            $query->whereIn('subject_id', explode(',', $subject_ids));
        }
        $scores = $query->where('student_id', $student_id)
            ->orderBy('score', 'desc')
            ->with(['student', 'subject'])->paginate(10);
        return response()->json(['data' => $scores], 200);
    }

    public function subjects(Request $request)
    {
        return response()->json(['data' => Subject::all()], 200);
    }

    public function scoreRate(Request $request)
    {
        $query = Score::query();
        if ($subject_id = $request->subject_id) {
            $query->where('subject_id', $subject_id);

        }

        $scores = $query->paginate(10);
        $result = [];
        foreach ($scores as $score) {
            $ex_no = Score::where(['grade' => '优秀', 'test_date' => $score->test_date])->count();
            $jg_no = Score::where(['grade' => '及格', 'test_date' => $score->test_date])->count();
            $lh_no = Score::where(['grade' => '良好', 'test_date' => $score->test_date])->count();

            $max_score = Score::where('test_date', $score->test_date)->max('score');
            $yk_no = Score::where('test_date', $score->test_date)->value('yk_percent');
            $result[] = [
                'test_date' => $score->test_date,
                'subject' => $score->subject,
                'cy_rate' => number_format($yk_no / $score->yk_number * 100, 2) . '%',
                'ex_rate' => number_format($ex_no / $score->yk_percent * 100, 2) . '%',
                'jg_rate' => number_format($jg_no / $score->yk_percent * 100, 2) . '%',
                'lh_rate' => number_format($lh_no / $score->yk_percent * 100, 2) . '%',
                'max_score' => $max_score . $score->subject->unit,
                'yk_number' => $score->yk_number,
                'yk_percent' => $score->yk_percent,
            ];
        }

//        $result = $scores->map(function ($score) {
//            $ex_no = Score::where(['grade' => '优秀', 'test_date' => $score->test_date])->count();
//            $jg_no = Score::where(['grade' => '及格', 'test_date' => $score->test_date])->count();
//            $lh_no = Score::where(['grade' => '良好', 'test_date' => $score->test_date])->count();
//
//            $max_score = Score::where('test_date', $score->test_date)->max('score');
//            $yk_no = Score::where('test_date', $score->test_date)->value('yk_percent');
//
//            return [
//                'test_date' => $score->test_date,
//                'subject' => $score->subject,
//                'cy_rate' => number_format($yk_no / $score->yk_number * 100, 2) . '%',
//                'ex_rate' => number_format($ex_no / $score->yk_percent * 100, 2) . '%',
//                'jg_rate' => number_format($jg_no / $score->yk_percent * 100, 2) . '%',
//                'lh_rate' => number_format($lh_no / $score->yk_percent * 100, 2) . '%',
//                'max_score' => $max_score . $score->subject->unit,
//                'yk_number' => $score->yk_number,
//                'yk_percent' => $score->yk_percent,
//            ];
//
//        });
//        // 获取当前分页页码
//        $currentPage = LengthAwarePaginator::resolveCurrentPage();
//
//        // 设置每页显示的数据条数
//        $perPage = 10;
//
//        // 分割集合为指定大小的分页数据
//        $currentPageItems = $result->slice(($currentPage - 1) * $perPage, $perPage)->values();
//
//        // 创建分页实例
//        $paginatedData = new LengthAwarePaginator(
//            $currentPageItems, // 当前页的数据
//            $result->count(), // 总数据量
//            $perPage, // 每页条数
//            $currentPage, // 当前页码
//            ['path' => $request->url(), 'query' => $request->query()] // 保持 URL 参数
//        );
        return response()->json(['data' => $result, 'score' => $scores], 200);

    }

    public function batchScore(Request $request)
    {
        $student_ids = $request->student_ids;
        $form = $request->form;
        foreach ($student_ids as $key => $student_id) {
            $score = Score::create([
                'student_id' => $student_id[0],
                'subject_id' => $form['subject_id'],
                'test_date' => $form['test_date'],
                'score' => $student_id[1],
                'grade' => $student_id[2],
                'yk_number' => $form['yk_number'],
                'yk_percent' => $form['yk_percent'],
            ]);
        }
        return response()->json(['data' => $score], 200);
    }

    public function students()
    {
        return response()->json(['data' => Student::all()], 200);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $score = Score::create($request->all());
        return response()->json(['data' => $score], 200);
    }

    /**
     * Display the specified resource.
     */
    public function show(Score $score)
    {
        return response()->json(['data' => $score], 200);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Score $score)
    {
        $score = $score->update($request->all());
        return response()->json(['data' => $score], 200);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Score $score)
    {
        $score = $score->delete();
        return response()->json(['data' => $score], 200);
    }

    public function importScore(Request $request)
    {
        Excel::import(new ScoreImport, $request->file('file'));

        return response()->json(['message' => '导入成功']);
    }
}
